<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon.ico">
  <link rel="mask-icon" href="/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.loli.net/css?family=Lato:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha256-DfWjNxDkM94fVBWx1H5BMMp0Zq7luBlV8QRcSES7s+0=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/blue/pace-theme-bounce.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"www.kaaaaai.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.12.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="最近在优化一个项目的过程，过程中发现之前开发时由于刚接触 Swift 的原因，在 Swift 中的类里使用了很多 OC 的写法，比如字典数组对象会习惯性用 NSDictionary、NSArray来初始化，而不是用 [KeyType: ValueType]() 或是 [SomeType]() 这种类型来实例化变量。虽然在使用上没有什么问题，但看起来多少有点。。。不优雅。　　当我把大部分类型都修">
<meta property="og:type" content="article">
<meta property="og:title" content="Swift - ?和!的学习">
<meta property="og:url" content="https://www.kaaaaai.cn/swift-optional-and-unwrapping-learning.html">
<meta property="og:site_name" content="壹拾肆">
<meta property="og:description" content="最近在优化一个项目的过程，过程中发现之前开发时由于刚接触 Swift 的原因，在 Swift 中的类里使用了很多 OC 的写法，比如字典数组对象会习惯性用 NSDictionary、NSArray来初始化，而不是用 [KeyType: ValueType]() 或是 [SomeType]() 这种类型来实例化变量。虽然在使用上没有什么问题，但看起来多少有点。。。不优雅。　　当我把大部分类型都修">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-04-24T09:24:52.000Z">
<meta property="article:modified_time" content="2020-11-21T02:09:49.000Z">
<meta property="article:author" content="Kaaaaai">
<meta property="article:tag" content="EXP">
<meta property="article:tag" content="iOS">
<meta property="article:tag" content="Swift">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://www.kaaaaai.cn/swift-optional-and-unwrapping-learning.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://www.kaaaaai.cn/swift-optional-and-unwrapping-learning.html","path":"/swift-optional-and-unwrapping-learning.html","title":"Swift - ?和!的学习"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Swift - ?和!的学习 | 壹拾肆</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-102185873-1"></script>
  <script class="next-config" data-name="google_analytics" type="application/json">{"tracking_id":"UA-102185873-1","only_pageview":false}</script>
  <script src="/js/third-party/analytics/google-analytics.js"></script>

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?9578d14210d67becef48447e4f6b3f20"></script>



<link rel="dns-prefetch" href="https://waline-server-kaaaaai.vercel.app"> <script type="text/javascript" src="/js/link-highlight.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="壹拾肆" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">壹拾肆</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">有些安排是多余的 这片空旷对我有益</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-moments"><a href="/bb/" rel="section"><i class="fa fa-coffee fa-fw"></i>碎片</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%92%8C-%EF%BC%81-%E6%98%AF%E8%A1%A8%E7%A4%BA%E4%B8%A4%E7%A7%8D%E4%B8%8D%E5%90%8C%E7%9A%84%E7%B1%BB%E5%9E%8B%E5%90%97%EF%BC%8C%E4%B8%80%E7%A7%8D%E6%98%AF%E5%8F%AF%E4%BB%A5%E4%B8%BA%E7%A9%BA%EF%BC%8C%E4%B8%80%E7%A7%8D%E4%B8%8D%E5%8F%AF%E4%BB%A5%E4%B8%BA%E7%A9%BA%EF%BC%9F"><span class="nav-number">1.</span> <span class="nav-text">? 和 ！ 是表示两种不同的类型吗，一种是可以为空，一种不可以为空？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E-Unconditional-Unwrapping"><span class="nav-number">2.</span> <span class="nav-text">关于 Unconditional Unwrapping</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B6%E4%BB%96"><span class="nav-number">3.</span> <span class="nav-text">其他</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Kaaaaai"
      src="https://s2.loli.net/2022/03/29/GSJKrCRi4owa9hq.png">
  <p class="site-author-name" itemprop="name">Kaaaaai</p>
  <div class="site-description" itemprop="description">🐨🐨</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">100</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="sidebar-button site-overview-item animated">
    <button><i class="fa fa-comment"></i>
      Chat
    </button>
  </div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/Kaaaaai" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Kaaaaai" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://stackoverflow.com/users/8342030/kaaaaai" title="StackOverflow → https:&#x2F;&#x2F;stackoverflow.com&#x2F;users&#x2F;8342030&#x2F;kaaaaai" rel="noopener" target="_blank"><i class="fab fa-stack-overflow fa-fw"></i>StackOverflow</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.instagram.com/edisonlllllk" title="Instagram → https:&#x2F;&#x2F;www.instagram.com&#x2F;edisonlllllk" rel="noopener" target="_blank"><i class="fab fa-instagram fa-fw"></i>Instagram</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:root@kaaaaai.cn" title="E-Mail → mailto:root@kaaaaai.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



        </div>
      </div>

      
    <!-- 网易云歌曲 -->
    <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=421203025&auto=1&height=66"></iframe>
        <div class="back-to-top animated" role="button" aria-label="返回顶部">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://www.kaaaaai.cn/swift-optional-and-unwrapping-learning.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://s2.loli.net/2022/03/29/GSJKrCRi4owa9hq.png">
      <meta itemprop="name" content="Kaaaaai">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="壹拾肆">
      <meta itemprop="description" content="🐨🐨">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Swift - ?和!的学习 | 壹拾肆">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Swift - ?和!的学习
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-04-24 17:24:52" itemprop="dateCreated datePublished" datetime="2020-04-24T17:24:52+08:00">2020-04-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index"><span itemprop="name">笔记</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
  
  <span class="post-meta-item">
    
    <span class="post-meta-item-icon">
      <i class="far fa-comment"></i>
    </span>
    <span class="post-meta-item-text">Waline：</span>
  
    <a title="waline" href="/swift-optional-and-unwrapping-learning.html#waline" itemprop="discussionUrl">
      <span class="post-comments-count waline-comment-count" data-path="/swift-optional-and-unwrapping-learning.html" itemprop="commentCount"></span>
    </a>
  </span>
  
  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>2.8k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>3 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>　　最近在优化一个项目的过程，过程中发现之前开发时由于刚接触 <code>Swift</code> 的原因，在 <code>Swift</code> 中的类里使用了很多 <code>OC</code> 的写法，比如字典数组对象会习惯性用 <code>NSDictionary</code>、<code>NSArray</code>来初始化，而不是用 <code>[KeyType: ValueType]()</code> 或是 <code>[SomeType]()</code> 这种类型来实例化变量。虽然在使用上没有什么问题，但看起来多少有点。。。不优雅。<br>　　当我把大部分类型都修改成 <code>Swift</code> 中的写法后（部分未修改是因为使用 <code>String</code> 类型来给文本做截取和富文本定义，实在不如 <code>NSString</code> 顺手，这种不顺手让我不由想起 Stack Overflow 上看到的一个评论：I thougt i already getting along well  with Swift.）发现，原来一些变量是否为空的判断中，使用 <code>Swift</code> 里的 <code>optional</code> 类型会方便很多。<br>　　比如解析一个 json 数据，如果层级多而且里面每个元素都是不确定的，那么可能就需要每个层级都判一次空。而如果使用 ? 来设置当前对象为可选值，只需要在最后一层实际使用到对象值时，判一次空就 OK 了。<br>　　对于 ? 和 ! 的区别和总结，网上有很多文章，在这里就不重复造轮子了。下面就对这个 <code>optional</code> 的自己两个疑问做个记录。
　　</p>
<h2 id="和-！-是表示两种不同的类型吗，一种是可以为空，一种不可以为空？"><a href="#和-！-是表示两种不同的类型吗，一种是可以为空，一种不可以为空？" class="headerlink" title="? 和 ！ 是表示两种不同的类型吗，一种是可以为空，一种不可以为空？"></a>? 和 ！ 是表示两种不同的类型吗，一种是可以为空，一种不可以为空？</h2><p>　　刚开始使用的时候没做深入了解，以为 <code>optional</code> 中的 ? 和 ! 和 <code>let</code> 声明不可变变量，<code>var</code> 声明可变变量。? 和 ! 是一组彼此相对只是含义不同的两个符号。但深入了解了一下，发现并不是这样，引用两段官方的文档：</p>
<blockquote>
<p>You use the Optional type whenever you use optional values, even if you never type the word Optional. Swift’s type system usually shows the wrapped type’s name with a trailing question mark (?) instead of showing the full type name. For example, if a variable has the type Int?, that’s just another way of writing Optional<Int>. The shortened form is preferred for ease of reading and writing code.</p>
<p>The types of shortForm and longForm in the following code sample are the same:</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> shortForm: <span class="built_in">Int</span>? = <span class="built_in">Int</span>(<span class="string">&quot;42&quot;</span>)</span><br><span class="line"><span class="keyword">let</span> longForm: Optional&lt;<span class="built_in">Int</span>&gt; = <span class="built_in">Int</span>(<span class="string">&quot;42&quot;</span>)</span><br></pre></td></tr></table></figure>
</blockquote>
<p>　　这里的意思是说当你使用 <code>Optional</code> 类型时的值，即使在初始化时没有用“Optional”这个单词指定类型，在 Swift 中也可用 ? 代替。即 <code>Int?</code> 等于 <code>Optional&lt;Int&gt;</code>。那按照之前我的理解，是否 ! 也是某个 Not Optional 单词的代替？后面官方文档就有提到了：</p>
<blockquote>
<p>When you’re certain that an instance of Optional contains a value, you can unconditionally unwrap the value by using the forced unwrap operator (postfix !). For example, the result of the failable Int initializer is unconditionally unwrapped in the example below.</p>
</blockquote>
<p>　　意思是说 ! 是代表一种 <code>Unconditional Unwrapping</code> 的运算符，而并不是作为一种类型的表达。
　　</p>
<h2 id="关于-Unconditional-Unwrapping"><a href="#关于-Unconditional-Unwrapping" class="headerlink" title="关于 Unconditional Unwrapping"></a>关于 Unconditional Unwrapping</h2><p>　　<code>Unconditional Unwrapping</code> 怎么理解，直译的话叫<strong>无条件展开</strong>，专业术语叫<strong>强制拆包</strong>。为什么使用 <code>Optional</code> 类型会需要强制拆包，如果使用 ! 运算符意味着强制拆包，那不使用 ! 时，<code>Optional</code> 是否还会做拆包的处理呢？<br>　　仍然回到官方文档，有这句：</p>
<blockquote>
<p>The Optional type is an enumeration with two cases. Optional.none is equivalent to the nil literal.</p>
</blockquote>
<p>　　也就是说 <code>Optional</code> 是一个默认带有 <code>Optional.none</code> 枚举类型的包装。所以使用时我们必须按官方说的：</p>
<blockquote>
<p>You must unwrap the value of an Optional instance before you can use it in many contexts.</p>
</blockquote>
<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><p>　　基于以上的学习和理解，我们可以来解读以下一些写法：</p>
<figure class="highlight swift"><figcaption><span>初始化</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> value:<span class="type">NSString</span> <span class="operator">=</span> <span class="literal">nil</span> <span class="comment">//错误写法，未指定 Optional，所以不可以被赋值为空</span></span><br><span class="line"><span class="keyword">let</span> value:<span class="type">NSString</span>! <span class="comment">//如果后续未赋值而直接使用则会崩溃</span></span><br><span class="line"><span class="keyword">let</span> value:<span class="type">NSString</span>? <span class="operator">=</span> <span class="literal">nil</span> <span class="comment">//同下，如果后续 value 未被赋值，他会默认等于 nil</span></span><br><span class="line"><span class="keyword">let</span> value:<span class="type">NSString</span>?</span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><figcaption><span>转换类型</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> array:<span class="type">NSArray</span> <span class="operator">=</span> <span class="type">NSMutableArray</span>.<span class="keyword">init</span>(object: <span class="string">&quot;111&quot;</span>)</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">(111)</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="built_in">print</span>(array <span class="keyword">as!</span> <span class="type">NSMutableArray</span>)</span><br><span class="line"> </span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">Optional(&lt;__NSArrayM 0x7b790430&gt;(111))</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="built_in">print</span>(array <span class="keyword">as?</span> <span class="type">NSMutableArray</span>)</span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><figcaption><span>方法定义</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//可传空值</span></span><br><span class="line"><span class="keyword">func</span> <span class="title function_">buttonClick</span>(<span class="params">sender</span>: <span class="type">UIButton</span>?)&#123;</span><br><span class="line">    <span class="comment">//....    </span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//不可传空值</span></span><br><span class="line"><span class="keyword">func</span> <span class="title function_">buttonClick</span>(<span class="params">sender</span>: <span class="type">UIButton</span>)&#123;</span><br><span class="line">    <span class="comment">//....    </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> fruitDic: [<span class="type">String</span>: <span class="type">String</span>] <span class="operator">=</span> [<span class="string">&quot;apple&quot;</span>:<span class="string">&quot;red&quot;</span>,<span class="string">&quot;banana&quot;</span>:<span class="string">&quot;yellow&quot;</span>]</span><br><span class="line"><span class="keyword">let</span> apple: <span class="type">String</span>! <span class="operator">=</span> fruitDic[<span class="string">&quot;apple&quot;</span>]<span class="operator">!</span> <span class="comment">// String! 可以直接写成 String，这里只是为了直观阅读</span></span><br><span class="line"><span class="keyword">let</span> banana: <span class="type">String</span>? <span class="operator">=</span> fruitDic[<span class="string">&quot;apple&quot;</span>]</span><br><span class="line"><span class="keyword">let</span> blueberry: <span class="type">String</span>! <span class="operator">=</span> fruitDic[<span class="string">&quot;blueberry&quot;</span>] <span class="operator">??</span> <span class="string">&quot;&quot;</span></span><br><span class="line"><span class="keyword">let</span> orange: <span class="type">String</span>? <span class="operator">=</span> fruitDic[<span class="string">&quot;orange&quot;</span>]</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button>
    请喝咖啡
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/loading-style-3.gif" data-original="https://s2.loli.net/2022/07/02/Gce8a5QAqrZ3X9R.gif" alt="Kaaaaai 微信">
        <span>微信</span>
      </div>

  </div>
</div>

          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Kaaaaai
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://www.kaaaaai.cn/swift-optional-and-unwrapping-learning.html" title="Swift - ?和!的学习">https://www.kaaaaai.cn/swift-optional-and-unwrapping-learning.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/EXP/" rel="tag"><i class="fa fa-tag"></i> EXP</a>
              <a href="/tags/iOS/" rel="tag"><i class="fa fa-tag"></i> iOS</a>
              <a href="/tags/Swift/" rel="tag"><i class="fa fa-tag"></i> Swift</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/literary-memoirs-reading-notes.html" rel="prev" title="《文学回忆录》读书笔记">
                  <i class="fa fa-chevron-left"></i> 《文学回忆录》读书笔记
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/web-resolve-recirculation-errors.html" rel="next" title="解决使用 GitPage 重定向多次问题">
                  解决使用 GitPage 重定向多次问题 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="waline"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kaaaaai</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">234k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">3:33</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <!-- time -->
  <div id="show-time">
    <span id="span_dt_dt"></span>
  </div>
  <script>
      function show_date_time() {
        window.setTimeout("show_date_time()", 1000);
        BirthDay = new Date("6/23/2017 19:37:01");
        today = new Date();
        //总时间
        timeold = (today.getTime() - BirthDay.getTime());
        sectimeold = timeold / 1000
        secondsold = Math.floor(sectimeold);
        msPerDay = 24 * 60 * 60 * 1000
        e_daysold = timeold / msPerDay
        daysold = Math.floor(e_daysold);
        e_hrsold = (e_daysold - daysold) * 24;
        hrsold = Math.floor(e_hrsold);
        e_minsold = (e_hrsold - hrsold) * 60;
        minsold = Math.floor((e_hrsold - hrsold) * 60);
        seconds = Math.floor((e_minsold - minsold) * 60);
        span_dt_dt.innerHTML = "已存活 " + daysold + " 天 " + hrsold + " 小时 " + minsold + " 分 " + seconds + " 秒";
    }
    show_date_time();
  </script>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.5.0/pjax.min.js" integrity="sha256-3NkoLDrmHLTYj7csHIZSr0MHAFTXth7Ua/DDt4MRUAg=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  
<script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>
<script class="next-config" data-name="chatra" type="application/json">{"enable":true,"async":true,"id":"QXLRxXcsfrRJR2KTG"}</script>
<script src="/js/third-party/chat/chatra.js"></script>
<script async src="https://call.chatra.io/chatra.js"></script>



  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>

  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<script class="next-config" data-name="waline" type="application/json">{"lang":"zh-cn","enable":true,"serverURL":"https://waline-server-kaaaaai.vercel.app","cssUrl":"https://unpkg.com/@waline/client@v2/dist/waline.css","commentCount":true,"pageview":false,"placeholder":"请文明评论呀","avatar":"mm","meta":["nick","mail","link"],"pageSize":10,"visitor":false,"comment_count":true,"requiredFields":[],"libUrl":"//unpkg.com/@waline/client@v2/dist/waline.js","el":"#waline","comment":true,"path":"/swift-optional-and-unwrapping-learning.html"}</script>
<link rel="stylesheet" href="https://unpkg.com/@waline/client@v2/dist/waline.css">
<script>
document.addEventListener('page:loaded', () => {
  NexT.utils.loadComments(CONFIG.waline.el).then(() =>
    NexT.utils.getScript(CONFIG.waline.libUrl, { condition: window.Waline })
  ).then(() => 
    Waline.init(Object.assign({}, CONFIG.waline,{ el: document.querySelector(CONFIG.waline.el) }))
  );
});
</script>


        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: true,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var a=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,d=o();function o(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(t){(a||t)&&(d=o());for(var e,i=0;i<d.length;i++)0<=(e=(e=d[i]).getBoundingClientRect()).bottom&&0<=e.left&&e.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,a,n,o=d[i];e=function(){d=d.filter(function(t){return o!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(o)},(t=o).dataset.loaded||(t.hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(a=new Image,n=t.getAttribute("data-original"),a.onload=function(){t.src=n,t.removeAttribute("data-original"),t.setAttribute("data-loaded",!0),e&&e()},a.onerror=function(){t.removeAttribute("data-original"),t.setAttribute("data-loaded",!1),t.src=n},t.src!==n&&(a.src=n)))}()}function e(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",e),r.addEventListener("resize",e),r.addEventListener("orientationchange",e)}(this);</script></body>
</html>
